package com.example.article.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.article.mapper.ArticleMapper;
import com.example.article.service.ArticleService;
import com.example.common.constants.ArticleConstants;
import com.example.common.constants.BehaviorConstants;
import com.example.common.redis.CacheService;
import com.example.common.util.R;
import com.example.common.util.ResultCodeRecord;
import com.example.model.article.dto.ArticleHomeDto;
import com.example.model.article.dto.ArticleInfoDto;
import com.example.model.article.pojo.Article;
import com.example.model.article.vo.HotArticleVo;
import com.example.model.mess.ArticleVisitStreamMess;
import com.example.model.user.pojo.User;
import com.example.utils.thread.UserThreadLocal;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ArticleServiceImpl extends ServiceImpl< ArticleMapper, Article > implements ArticleService {
    public static final Integer DEFAULT_SIZE = 10;
    public static final Integer MAX_SIZE = 20;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private CacheService cacheService;

    @Override
    public Object queryLikesAndConllections(Integer userId, Date beginDate, Date endDate) {
        Map map = articleMapper.queryLikesAndConllections(userId, beginDate, endDate);
        return map;
    }

    @Override
    public List< Article > load(ArticleHomeDto homeDto, Short loadType) {
        // 1、校验参数
        // 分页条数的校验
        // 健壮性判断
        if (homeDto.getSize() == null || homeDto.getSize() < 0 || homeDto.getSize() > MAX_SIZE) {
            homeDto.setSize(DEFAULT_SIZE);
        }
        // 时间
        if (homeDto.getMaxBehotTime() == null) {
            homeDto.setMinBehotTime(new Date());
        }
        if (homeDto.getMaxBehotTime() == null) {
            homeDto.setMaxBehotTime(new Date());
        }
        // 2、查询
        List< Article > articleList = articleMapper.loadArticle(homeDto, loadType);
        // 3、结果返回
        return articleList;
    }

    @Override
    public Object loadArticleListV2(ArticleHomeDto articleHomeDto, Short type, boolean firstPage) {
        if (firstPage) {
            // 从缓存中获取数据
            String articleListStr = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + articleHomeDto.getTag());
            if (!StringUtils.isEmpty(articleListStr)) {
                List< HotArticleVo > articleVoList = JSON.parseArray(articleListStr, HotArticleVo.class);
                return articleVoList;
            }
        }
        return load(articleHomeDto, type);
    }

    @Override
    public Object loadArticleBehavior(ArticleInfoDto articleInfoDto) {

        //0.检查参数
        if (articleInfoDto == null || articleInfoDto.getArticleId() == null || articleInfoDto.getAuthorId() == null) {
            return R.error(ResultCodeRecord.PARAM_INVALID);
        }

        //{ "isfollow": true, "islike": true,"isunlike": false,"iscollection": true }
        boolean isfollow = false, islike = false, isunlike = false, iscollection = false;

        User user = UserThreadLocal.getUser();
        if(user != null){
            //喜欢行为
            String likeBehaviorJson = (String) cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + articleInfoDto.getArticleId().toString(), user.getUserId().toString());
            if(org.apache.commons.lang3.StringUtils.isNotBlank(likeBehaviorJson)){
                islike = true;
            }
            //不喜欢的行为
            String unLikeBehaviorJson = (String) cacheService.hGet(BehaviorConstants.UN_LIKE_BEHAVIOR + articleInfoDto.getArticleId().toString(), user.getUserId().toString());
            if(org.apache.commons.lang3.StringUtils.isNotBlank(unLikeBehaviorJson)){
                isunlike = true;
            }
            //是否收藏
            String collctionJson = (String) cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR+user.getUserId(),articleInfoDto.getArticleId().toString());
            if(org.apache.commons.lang3.StringUtils.isNotBlank(collctionJson)){
                iscollection = true;
            }

            //是否关注
            Double score = cacheService.zScore(BehaviorConstants.APUSER_FOLLOW_RELATION + user.getUserId(), articleInfoDto.getAuthorId().toString());
            System.out.println(score);
            if(score != null){
                isfollow = true;
            }

        }

        Map<String, Object> map = new HashMap<>();
        map.put("isfollow", isfollow);
        map.put("islike", islike);
        map.put("isunlike", isunlike);
        map.put("iscollection", iscollection);

        return map;
    }


    /**
     * 更新文章的分值  同时更新缓存中的热点文章数据
     *
     * @param articleVisitStreamMess
     */
    @Override
    public boolean updateScore(ArticleVisitStreamMess articleVisitStreamMess) {
        //1.更新文章的阅读、点赞、收藏、评论的数量
        Article article = updateArticle(articleVisitStreamMess);
        //2.计算文章的分值
        Integer score = computeScore(article);
        score = score * 3;

        //3.替换当前文章对应频道的热点数据
        replaceDataToRedis(article, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + article.getChannelId());

        //4.替换推荐对应的热点数据
        replaceDataToRedis(article, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
        return true;
    }

    /**
     * 更新文章行为数量
     *
     * @param articleVisitStreamMess
     */
    private Article updateArticle(ArticleVisitStreamMess articleVisitStreamMess) {
        Article article = getById(articleVisitStreamMess.getArticleId());
        article.setArticleCollection(article.getArticleCollection() == null ? 0 : article.getArticleCollection() + articleVisitStreamMess.getCollect());
        article.setArticleComment(article.getArticleComment() == null ? 0 : article.getArticleComment() + articleVisitStreamMess.getComment());
        article.setArticleLikes(article.getArticleLikes() == null ? 0 : article.getArticleLikes() + articleVisitStreamMess.getLike());
        article.setArticleViews(article.getArticleViews() == null ? 0 : article.getArticleViews() + articleVisitStreamMess.getView());
        updateById(article);
        return article;

    }

    /**
     * 计算文章的具体分值
     *
     * @param article
     * @return
     */
    private Integer computeScore(Article article) {
        Integer score = 0;
        if (article.getArticleLikes() != null) {
            score += article.getArticleLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if (article.getArticleViews() != null) {
            score += article.getArticleViews();
        }
        if (article.getArticleComment() != null) {
            score += article.getArticleComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if (article.getArticleCollection() != null) {
            score += article.getArticleCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return score;
    }

    /**
     * 替换数据并且存入到redis
     *
     * @param article
     * @param score
     * @param s
     */
    private void replaceDataToRedis(Article article, Integer score, String s) {
        String articleListStr = cacheService.get(s);
        if (org.apache.commons.lang3.StringUtils.isNotBlank(articleListStr)) {
            List< HotArticleVo > hotArticleVoList = JSON.parseArray(articleListStr, HotArticleVo.class);

            boolean flag = true;

            //如果缓存中存在该文章，只更新分值
            for (HotArticleVo hotArticleVo : hotArticleVoList) {
                if (hotArticleVo.getArticleId().equals(article.getArticleId())) {
                    hotArticleVo.setScore(score);
                    flag = false;
                    break;
                }
            }

            //如果缓存中不存在，查询缓存中分值最小的一条数据，进行分值的比较，如果当前文章的分值大于缓存中的数据，就替换
            if (flag) {
                if (hotArticleVoList.size() >= 30) {
                    hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
                    HotArticleVo lastHot = hotArticleVoList.get(hotArticleVoList.size() - 1);
                    if (lastHot.getScore() < score) {
                        hotArticleVoList.remove(lastHot);
                        HotArticleVo hot = new HotArticleVo();
                        BeanUtils.copyProperties(article, hot);
                        hot.setScore(score);
                        hotArticleVoList.add(hot);
                    }


                } else {
                    HotArticleVo hot = new HotArticleVo();
                    BeanUtils.copyProperties(article, hot);
                    hot.setScore(score);
                    hotArticleVoList.add(hot);
                }
            }
            //缓存到redis
            hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
            cacheService.set(s, JSON.toJSONString(hotArticleVoList));
        }
    }
}